import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../models/expense_model.dart';
import '../providers/expense_providers.dart';
import '../themes/expense_theme.dart';
import '../widgets/enhanced_date_picker.dart';

/// 添加/编辑记账条目界面
class AddExpenseScreen extends ConsumerStatefulWidget {
  final ExpenseModel? expense; // 如果不为空，则为编辑模式
  final ExpenseType? initialType; // 初始类型

  const AddExpenseScreen({super.key, this.expense, this.initialType});

  @override
  ConsumerState<AddExpenseScreen> createState() => _AddExpenseScreenState();
}

class _AddExpenseScreenState extends ConsumerState<AddExpenseScreen>
    with TickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();
  final _descriptionController = TextEditingController();

  late ExpenseType _selectedType;
  ExpenseCategory? _selectedCategory;
  DateTime _selectedDate = DateTime.now();
  bool _isLoading = false;

  // 动画控制器
  late AnimationController _slideAnimationController;
  late AnimationController _fadeAnimationController;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _slideAnimationController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );
    _fadeAnimationController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _slideAnimation =
        Tween<Offset>(begin: const Offset(0, 0.3), end: Offset.zero).animate(
          CurvedAnimation(
            parent: _slideAnimationController,
            curve: Curves.easeOutCubic,
          ),
        );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _fadeAnimationController,
        curve: Curves.easeInOut,
      ),
    );

    if (widget.expense != null) {
      // 编辑模式
      final expense = widget.expense!;
      _amountController.text = expense.amount.toString();
      _descriptionController.text = expense.description;
      _selectedType = expense.type;
      _selectedCategory = expense.category;
      _selectedDate = expense.date;
    } else {
      // 新增模式
      _selectedType = widget.initialType ?? ExpenseType.expense;
    }

    // 启动动画
    _fadeAnimationController.forward();
    _slideAnimationController.forward();
  }

  @override
  void dispose() {
    _amountController.dispose();
    _descriptionController.dispose();
    _slideAnimationController.dispose();
    _fadeAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ExpenseTheme.background,
      appBar: AppBar(
        title: Text(widget.expense != null ? '编辑记录' : '添加记录'),
        backgroundColor: ExpenseTheme.primaryBlue,
        foregroundColor: Colors.white,
        elevation: 0,
        flexibleSpace: Container(
          decoration: BoxDecoration(gradient: ExpenseTheme.primaryGradient),
        ),
      ),
      body: FadeTransition(
        opacity: _fadeAnimation,
        child: SlideTransition(
          position: _slideAnimation,
          child: Form(
            key: _formKey,
            child: SingleChildScrollView(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 类型选择
                  _buildAnimatedCard(_buildTypeSelector(), 0),

                  SizedBox(height: 24.h),

                  // 金额输入
                  _buildAnimatedCard(_buildAmountInput(), 1),

                  SizedBox(height: 24.h),

                  // 分类选择
                  _buildAnimatedCard(_buildCategorySelector(), 2),

                  SizedBox(height: 24.h),

                  // 日期选择
                  _buildAnimatedCard(_buildDateSelector(), 3),

                  SizedBox(height: 24.h),

                  // 备注输入
                  _buildAnimatedCard(_buildDescriptionInput(), 4),

                  SizedBox(height: 32.h),

                  // 保存按钮
                  _buildAnimatedCard(_buildSaveButton(), 5),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建带动画的卡片
  Widget _buildAnimatedCard(Widget child, int index) {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 300 + (index * 100)),
      tween: Tween<double>(begin: 0.0, end: 1.0),
      curve: Curves.easeOutCubic,
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 20 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: Container(
              decoration: BoxDecoration(
                color: ExpenseTheme.cardBackground,
                borderRadius: BorderRadius.circular(16.r),
                boxShadow: [
                  BoxShadow(
                    color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              padding: EdgeInsets.all(20.w),
              child: child,
            ),
          ),
        );
      },
      child: child,
    );
  }

  /// 构建类型选择器
  Widget _buildTypeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(Icons.category, color: ExpenseTheme.primaryBlue, size: 20.sp),
            SizedBox(width: 8.w),
            Text(
              '记账类型',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                color: ExpenseTheme.textPrimary,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        SizedBox(height: 16.h),
        Row(
          children: [
            Expanded(
              child: _buildTypeOption(
                ExpenseType.income,
                '收入',
                Icons.trending_up,
                ExpenseTheme.incomeGreen,
              ),
            ),
            SizedBox(width: 16.w),
            Expanded(
              child: _buildTypeOption(
                ExpenseType.expense,
                '支出',
                Icons.trending_down,
                ExpenseTheme.expenseRed,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建类型选项
  Widget _buildTypeOption(
    ExpenseType type,
    String label,
    IconData icon,
    Color color,
  ) {
    final isSelected = _selectedType == type;

    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      child: InkWell(
        onTap: () {
          setState(() {
            _selectedType = type;
            _selectedCategory = null; // 重置分类选择
          });
        },
        borderRadius: BorderRadius.circular(16.r),
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 16.w),
          decoration: BoxDecoration(
            gradient: isSelected
                ? LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      color.withValues(alpha: 0.1),
                      color.withValues(alpha: 0.05),
                    ],
                  )
                : null,
            color: isSelected ? null : ExpenseTheme.softBlue,
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(
              color: isSelected ? color : ExpenseTheme.lightBlue,
              width: isSelected ? 2 : 1,
            ),
            boxShadow: isSelected
                ? [
                    BoxShadow(
                      color: color.withValues(alpha: 0.2),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ]
                : null,
          ),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: isSelected
                      ? color.withValues(alpha: 0.1)
                      : Colors.white,
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  icon,
                  color: isSelected ? color : ExpenseTheme.textSecondary,
                  size: 28.sp,
                ),
              ),
              SizedBox(height: 12.h),
              Text(
                label,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                  color: isSelected ? color : ExpenseTheme.textPrimary,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建金额输入
  Widget _buildAmountInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(
              Icons.monetization_on,
              color: ExpenseTheme.primaryBlue,
              size: 20.sp,
            ),
            SizedBox(width: 8.w),
            Text(
              '金额',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                color: ExpenseTheme.textPrimary,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
        SizedBox(height: 16.h),
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: TextFormField(
            controller: _amountController,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')),
            ],
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: ExpenseTheme.textPrimary,
            ),
            decoration: InputDecoration(
              hintText: '0.00',
              hintStyle: TextStyle(
                fontSize: 18.sp,
                color: ExpenseTheme.textLight,
              ),
              prefixIcon: Container(
                margin: EdgeInsets.all(12.w),
                padding: EdgeInsets.all(8.w),
                decoration: BoxDecoration(
                  color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Icon(
                  Icons.attach_money,
                  color: ExpenseTheme.primaryBlue,
                  size: 20.sp,
                ),
              ),
              filled: true,
              fillColor: Colors.white,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 20.w,
                vertical: 20.h,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.r),
                borderSide: BorderSide.none,
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.r),
                borderSide: BorderSide(color: ExpenseTheme.lightBlue, width: 1),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.r),
                borderSide: BorderSide(
                  color: ExpenseTheme.primaryBlue,
                  width: 2,
                ),
              ),
              errorBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(16.r),
                borderSide: BorderSide(
                  color: ExpenseTheme.expenseRed,
                  width: 1,
                ),
              ),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入金额';
              }
              final amount = double.tryParse(value);
              if (amount == null || amount <= 0) {
                return '请输入有效的金额';
              }
              return null;
            },
          ),
        ),
      ],
    );
  }

  /// 构建分类选择器
  Widget _buildCategorySelector() {
    final categories = _selectedType == ExpenseType.income
        ? ExpenseCategoryExtension.incomeCategories
        : ExpenseCategoryExtension.expenseCategories;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '分类',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            color: ExpenseTheme.textPrimary,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 12.h),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: categories.map((category) {
            final isSelected = _selectedCategory == category;
            return InkWell(
              onTap: () {
                setState(() {
                  _selectedCategory = category;
                });
              },
              borderRadius: BorderRadius.circular(8.r),
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                decoration: BoxDecoration(
                  color: isSelected
                      ? ExpenseTheme.primaryBlue.withValues(alpha: 0.1)
                      : ExpenseTheme.cardBackground,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(
                    color: isSelected
                        ? ExpenseTheme.primaryBlue
                        : ExpenseTheme.divider,
                    width: isSelected ? 2 : 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(category.icon, style: TextStyle(fontSize: 16.sp)),
                    SizedBox(width: 6.w),
                    Text(
                      category.displayName,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        color: isSelected
                            ? ExpenseTheme.primaryBlue
                            : ExpenseTheme.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
        if (_selectedCategory == null)
          Padding(
            padding: EdgeInsets.only(top: 8.h),
            child: Text(
              '请选择分类',
              style: TextStyle(fontSize: 12.sp, color: ExpenseTheme.expenseRed),
            ),
          ),
      ],
    );
  }

  /// 构建日期选择器
  Widget _buildDateSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '日期',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            color: ExpenseTheme.textPrimary,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 12.h),
        InkWell(
          onTap: _selectDate,
          borderRadius: BorderRadius.circular(12.r),
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: ExpenseTheme.softBlue,
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(color: ExpenseTheme.lightBlue, width: 1.w),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.calendar_today,
                  color: ExpenseTheme.primaryBlue,
                  size: 20.sp,
                ),
                SizedBox(width: 12.w),
                Text(
                  DateFormat(
                    'yyyy年MM月dd日 HH:mm',
                    'zh_CN',
                  ).format(_selectedDate),
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: ExpenseTheme.textPrimary,
                  ),
                ),
                const Spacer(),
                Icon(
                  Icons.arrow_forward_ios,
                  color: ExpenseTheme.textSecondary,
                  size: 16.sp,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建备注输入
  Widget _buildDescriptionInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '备注',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            color: ExpenseTheme.textPrimary,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 12.h),
        TextFormField(
          controller: _descriptionController,
          maxLines: 3,
          decoration: InputDecoration(
            hintText: '添加备注信息（可选）',
            filled: true,
            fillColor: ExpenseTheme.softBlue,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide(color: ExpenseTheme.lightBlue, width: 1),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12.r),
              borderSide: BorderSide(color: ExpenseTheme.primaryBlue, width: 2),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建保存按钮
  Widget _buildSaveButton() {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: _isLoading ? null : _saveExpense,
        style: ElevatedButton.styleFrom(
          backgroundColor: ExpenseTheme.primaryBlue,
          foregroundColor: Colors.white,
          padding: EdgeInsets.symmetric(vertical: 16.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
        ),
        child: _isLoading
            ? SizedBox(
                height: 20.h,
                width: 20.w,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              )
            : Text(
                widget.expense != null ? '更新记录' : '保存记录',
                style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
              ),
      ),
    );
  }

  /// 选择日期
  Future<void> _selectDate() async {
    final selectedDateTime = await showEnhancedDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now().add(const Duration(days: 365)),
      title: '选择记账日期',
      showTime: true,
      showQuickOptions: true,
    );

    if (selectedDateTime != null) {
      setState(() {
        _selectedDate = selectedDateTime;
      });
    }
  }

  /// 保存记账条目
  Future<void> _saveExpense() async {
    if (!_formKey.currentState!.validate() || _selectedCategory == null) {
      if (_selectedCategory == null) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请选择分类')));
      }
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final amount = double.parse(_amountController.text);
      final description = _descriptionController.text.trim();

      if (widget.expense != null) {
        // 编辑模式
        final updatedExpense = widget.expense!.copyWith(
          type: _selectedType,
          amount: amount,
          category: _selectedCategory!,
          description: description,
          date: _selectedDate,
        );
        await ref
            .read(expenseListProvider.notifier)
            .updateExpense(updatedExpense);
      } else {
        // 新增模式
        final newExpense = ExpenseModel.create(
          type: _selectedType,
          amount: amount,
          category: _selectedCategory!,
          description: description,
          date: _selectedDate,
        );
        await ref.read(expenseListProvider.notifier).addExpense(newExpense);
      }

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(widget.expense != null ? '记录已更新' : '记录已保存'),
            backgroundColor: ExpenseTheme.incomeGreen,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败: $e'),
            backgroundColor: ExpenseTheme.expenseRed,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
}
